package com.ysm.smfu.chat;

import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.activity.My_XiuGai_Activity;
import com.ysm.smfu.adapter.ContactAdapter;
import com.ysm.smfu.bean.Friend;
import com.ysm.smfu.bean.Friends;
import com.ysm.smfu.bean.SysMsg;
import com.ysm.smfu.fragment.BaseRefreshFragment;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.MySwipeListView;
import com.ysm.smfu.view.QuickIndexBar;
import com.ysm.smfu.view.RefreshLayout;
import com.hyphenate.chat.EMClient;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import chatuidemo.db.DBManager;
import chatuidemo.db.InviteMessgeDao;
import chatuidemo.ui.ChatActivity;
import easeui.EaseConstant;

/**
 * Created by Administrator on 2016/10/20.
 */
public class ZHContactListFragment extends BaseRefreshFragment<Friend> implements View.OnClickListener {

    @BindView(R.id.refresh)
    RefreshLayout refresh;
    @BindView(R.id.listView)
    MySwipeListView listView;
    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.quickIndex)
    QuickIndexBar quickIndexBar;
    private ContactAdapter adapter;
    private Map<String, Friend> contactList2;
    private TextView unreadMsgNumber;
    private TextView unreadMsgNumber2;
    private AutoLinearLayout xitong;
    private AutoLinearLayout shenqing;
    //    private AutoRelativeLayout searchF;
    private AutoLinearLayout fragment_my_qrcode;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = UIUtils.inflate(R.layout.fragment_contactlist_content);
        ButterKnife.bind(this, view);
        initRefresh(refresh, false, true);
        View view1 = UIUtils.inflate(R.layout.fragment_contactlist);
        initHeadView(view1);
        listView.addHeaderView(view1);
//        设置观察者，在同意之后，更新联系人,再登陆时，必然会加载联系人保存到本地，触发观察者，所以不需要主动获取联系人
        getActivity().getContentResolver().registerContentObserver(Uri.parse("content://dmh.contact"), true, observer);
        initData();
        return view;
    }


    //        刷新好友列表
    @Override
    public void load(boolean isLoad) {
        refreshContactList();
    }

    private void initHeadView(View view1) {
        unreadMsgNumber = (TextView) view1.findViewById(R.id.unread_msg_number);
        unreadMsgNumber2 = (TextView) view1.findViewById(R.id.unread_msg_number2);
        fragment_my_qrcode = (AutoLinearLayout) view1.findViewById(R.id.fragment_my_qrcode);
        xitong = (AutoLinearLayout) view1.findViewById(R.id.xitong);
        shenqing = (AutoLinearLayout) view1.findViewById(R.id.shenqing);
//        searchF = (AutoRelativeLayout) view1.findViewById(R.id.searchF);
//        searchF.setOnClickListener(this);
        xitong.setOnClickListener(this);
        shenqing.setOnClickListener(this);
        fragment_my_qrcode.setOnClickListener(this);
    }

    private ContentObserver observer = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            if (!isFromOnLine)
                getContactListFromLocal();
            isFromOnLine = false;
        }
    };
    boolean isStart;

    /**
     * 初始化数据
     */
    private void initData() {
        adapter = new ContactAdapter(datas, listView, getActivity());
        listView.setAdapter(adapter);
        adapter.setOnDelMsg(new ContactAdapter.OnDelMsg() {
            @Override
            public void onDelMsg(int position) {
                // 删除联系人
                DBManager.getInstance().deleteContact2(datas.get(position).id);
                EMClient.getInstance().chatManager().deleteConversation(datas.get(position).hxId, true);
                InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(UIUtils.getContext());
                inviteMessgeDao.deleteMessage(datas.get(position).hxId);
                delFriend(datas.get(position));
                datas.remove(position);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onOclikItem(int position) {
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
                if (isStart)
                    return;
//                重写条目点击事件
                String hxId = datas.get(position).hxId;
                PrintUtil.printRespones("聊天好友Id:" + hxId);
                UIUtils.startActivity(new Intent(UIUtils.getContext(), ChatActivity.class).putExtra(EaseConstant.EXTRA_USER_ID, hxId));
            }

            @Override
            public void onImageClick(int position) {
                Intent intent = new Intent(getActivity(), DetailFriendActivity.class);
                intent.putExtra("detailFriend", datas.get(position));
                getActivity().startActivity(intent);
            }
        });
        initListener();
    }

    public void setIsStart(boolean boo) {
        isStart = boo;
    }

    /**
     * 删除好友
     * /user/deleteFirend
     * id: 用户id   firendId :好友id
     */
    private void delFriend(final Friend friend) {
        BaseProtocal.builder(true).delFriend(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("删除好友", response);
                if (!TextUtils.isEmpty(response) && !TextUtils.equals(response, "{}")) {
                    String state = JsonUtil.getState(response);
                    if (TextUtils.equals(state, "1")) {
                        // 从数据库中去除好友
                        DBManager.getInstance().deleteContact2(friend.id);
                        DBManager.getInstance().deleteShenqingContact(friend.id);
                        //删除和某个user会话，如果需要保留聊天记录，传false
                        EMClient.getInstance().chatManager().deleteConversation(friend.hxId, true);
                        InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(UIUtils.getContext());
                        inviteMessgeDao.deleteMessage(friend.hxId);
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showErrToast();
            }
        }, friend.id);
    }

    private void initListener() {
        quickIndexBar.setOnLetterChangeListener(new QuickIndexBar.OnLetterChangeListener() {
            @Override
            public void onLetterChange(String letter) {
                for (int i = 0; i < datas.size(); i++) {
                    tvTips.setVisibility(View.VISIBLE);
                    tvTips.setText(letter);
                    Friend friend = datas.get(i);
                    String pinyin = friend.getPinYin();
                    if (TextUtils.equals(pinyin.charAt(0) + "", letter)) {
                        listView.setSelection(i);
                        break;
                    }
                }
            }

            @Override
            public void onReset() {
                tvTips.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 刷新联系人
     */
    private void refreshContactList() {
        getSQFriends();
        getRobotMsg();
        //异步获取好友列表
//        if (isNeedContact)
        getContactListFromOnLine();
    }


    /**
     * 是否通过下拉刷新从后台获取数据，如果是，则不需要再从数据库中获取
     */
    boolean isFromOnLine;

    /**
     * 从网络获取数据
     */
    private void getContactListFromOnLine() {
        BaseProtocal.builder(true).getContactListFromOnLine(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("好友列表", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    Friends friends = new Gson().fromJson(response, Friends.class);
                    List<Friend> user = friends.user;
                    isFromOnLine = true;
//                    ThreadUtils.runOnBackThread(new Runnable() {
//                        @Override
//                        public void run() {
                    DBManager.getInstance().saveContactList2(datas);
//                        }
//                    });
                    Collections.sort(user);
                    datas.clear();
                    datas.addAll(user);
                    adapter.notifyDataSetChanged();
                }
                setRefreshDone();
            }

            @Override
            public void onFail(Exception e) {
//                ToastUtils.showErrToast();
                setRefreshDone();
            }
        });
    }

    /**
     * 获取联系人列表
     */
    private void getContactListFromLocal() {
//        ThreadUtils.runOnBackThread(new Runnable() {
//            @Override
//            public void run() {
        PrintUtil.printRespones("从本地获取联系人");
        contactList2 = DBManager.getInstance().getContactList2();
        Set<String> keySet = contactList2.keySet();
        datas.clear();
        for (String key : keySet) {
            Friend friend = contactList2.get(key);
            datas.add(0, friend);
        }
        //   排序
        Collections.sort(datas);
//                ThreadUtils.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
        adapter.notifyDataSetChanged();
//                    }
//                });
//            }
//        });
    }

    /**
     * 获取好友申请数据
     */
    private void getSQFriends() {
        BaseProtocal.builder(true).getSQFriends(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("好友申请", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String state = jsonObject.optJSONObject("result").optString("state");
                    if (TextUtils.equals(state, "1")) {
                        int apply_size = jsonObject.optInt("apply-size");
                        setUnreadMsgNumber(apply_size);
                        Friends friends = new Gson().fromJson(response, Friends.class);
                        if (friends.user != null)
                            DBManager.getInstance().saveShenQingContact(friends.user);
                    }
                } catch (JSONException e) {

                }
            }

            @Override
            public void onFail(Exception e) {
//                ToastUtils.showErrToast();
            }
        });
    }

    /**
     * 获取系统消息
     * user/getSystemMessage
     * id: 用户id
     *
     * @return
     */
    public void getRobotMsg() {
        BaseProtocal.builder(true).getRobotMsg(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                SysMsg sysMsg = new Gson().fromJson(response, SysMsg.class);
                if (sysMsg != null && sysMsg.message != null && sysMsg.message.size() > 0) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        int unread_size = jsonObject.optInt("unread-size");
                        setUnReadSysMsgNumber(unread_size);
                    } catch (JSONException e) {

                    }
                    DBManager.getInstance().saveSysMsg(sysMsg);
                }
            }

            @Override
            public void onFail(Exception e) {
//                ToastUtils.showErrToast();
            }
        });
    }

    /**
     * 设置申请联系人
     */
    public void setUnreadMsgNumber(int count) {
        if (unreadMsgNumber2 == null)
            return;
        if (count > 0) {
            unreadMsgNumber2.setVisibility(View.VISIBLE);
            unreadMsgNumber2.setText(String.valueOf(count));
        } else {
            unreadMsgNumber2.setVisibility(View.GONE);
        }
    }

    public void setUnReadSysMsgNumber(int count) {
        if (unreadMsgNumber == null)
            return;
        if (count > 0) {
            unreadMsgNumber.setVisibility(View.VISIBLE);
            unreadMsgNumber.setText(String.valueOf(count));
        } else {
            unreadMsgNumber.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.xitong:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
//                获取系统消息
                UIUtils.startActivity(SysMsgActivity.class);
                setSysMsg();
                setUnReadSysMsgNumber(0);
                break;
            case R.id.shenqing:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
                Intent intent = new Intent(getActivity(), ShenqingFriendActivity.class);
                startActivityForResult(intent, 100);
                break;
//            case R.id.searchF:
//                UIUtils.startActivity(ZHSearchActivity.class);
//                break;
            case R.id.fragment_my_qrcode:
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
                //    二维码
                UIUtils.startActivity(My_XiuGai_Activity.class, "position", 2);
                break;

        }
    }

    /**
     * 设置系统消息
     * /user/setMessage
     * id
     */
    private void setSysMsg() {
        BaseProtocal.builder(true).setSysMsg(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                    PrintUtil.printRespones("设置系统消息为已读", response);
            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 101 && data != null) {
            int unCount = data.getIntExtra("unCount", -1);
            setUnreadMsgNumber(unCount);
        }
    }

    @Override
    public void refresh() {

    }

    /**
     * 清空联系人
     */
    public void clearContact() {
        datas.clear();
        if (adapter != null)
            adapter.notifyDataSetChanged();
        DBManager.getInstance().clearContactList();
        setUnreadMsgNumber(0);
        setUnReadSysMsgNumber(0);
    }
}
